package cn.kbyue.security.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;


/**
 * 决定请求是否允许通过 管理器
 * 这里功能为检查用户角色，是否能访问
 *
 * @author xl
 * @date 2020/4/19 16:00
 */
@Slf4j
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {

    /**
     * 决定用户的角色是否能访问
     * @param authentication 用户信息
     * @param object url
     * @param configAttributes 对应 FilterInvocationSecurityMetadataSource 设定的Attribute，例如用户的角色列表
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        log.info(">>> AccessDecisionManager 用户信息: {}", authentication);
        log.info(">>> 访问 url: {}, 需要的角色[code]： ConfigAttributes: {}", object, configAttributes);

        for (ConfigAttribute ca: configAttributes) {
            if (authentication instanceof AnonymousAuthenticationToken) {
                throw new BadCredentialsException("未登录!");
            }

            String needRole = ca.getAttribute();
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority: authorities) {
                DefinedGrantedAuthority grantedAuthority = (DefinedGrantedAuthority) authority;
                if (grantedAuthority.getAuthority().equals(needRole)) {
                    log.info(">>> 允许访问: hasRole: {}, needRole: {}", grantedAuthority.getAuthority(), needRole);
                    return;
                }
            }
        }
        throw new AccessDeniedException("请联系管理员分配权限！");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
